package pkg

import (
	"api/appconfig"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"strings"
	"time"
)

func AuthRealName(RealName string, IdCard string) bool {
	// 云市场分配的密钥Id
	secretId := appconfig.AppConf.RealNameConfig.SecretId
	// 云市场分配的密钥Key
	secretKey := appconfig.AppConf.RealNameConfig.SecretKey
	source := "market"

	// 签名
	auth, datetime, _ := calcAuthorization(source, secretId, secretKey)

	// 请求方法
	method := "POST"
	// 请求头
	headers := map[string]string{"X-Source": source, "X-Date": datetime, "Authorization": auth}

	// 查询参数
	queryParams := make(map[string]string)

	// body参数
	bodyParams := make(map[string]string)
	bodyParams["idcard_number"] = IdCard
	bodyParams["name"] = RealName
	//  fa
	url := "https://service-gtdwmbrg-1305308687.gz.apigw.tencentcs.com/release/id_card/real_name_validate"
	if len(queryParams) > 0 {
		url = fmt.Sprintf("%s?%s", url, urlencode(queryParams))
	}

	bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true}
	var body io.Reader = nil
	if bodyMethods[method] {
		body = strings.NewReader(urlencode(bodyParams))
		headers["Content-Type"] = "application/x-www-form-urlencoded"
	}

	client := &http.Client{
		Timeout: 5 * time.Second,
	}
	request, err := http.NewRequest(method, url, body)
	if err != nil {
		return false
	}
	for k, v := range headers {
		request.Header.Set(k, v)
	}
	response, err := client.Do(request)
	if err != nil {
		return false
	}
	defer response.Body.Close()

	bodyBytes, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return false
	}
	fmt.Println(string(bodyBytes))

	//反序列化
	var ret realNameRet
	err = json.Unmarshal(bodyBytes, &ret)
	if err != nil {
		return false
	}
	if ret.Code == 0 {
		return true
	}

	return false

}

type realNameRet struct {
	Msg    string `json:"msg"`
	Code   int    `json:"code"`
	TaskNo string `json:"taskNo"`
	Data   struct {
		Result   int    `json:"result"`
		Desc     string `json:"desc"`
		Sex      string `json:"sex"`
		Birthday string `json:"birthday"`
		Address  string `json:"address"`
	} `json:"data"`
}
